import { API_CONFIG } from '../config.js';

const BASE_URL = API_CONFIG.AUTH.BASE_URL;

function getToken() {
  if (typeof window === 'undefined') return null;
  return (
    localStorage.getItem('auth_token') ||
    sessionStorage.getItem('auth_token') ||
    null
  );
}

async function request(url, options = {}) {
  const token = getToken();
  const headers = {
    Accept: 'application/json',
    ...(options.body ? { 'Content-Type': 'application/json' } : {}),
    ...(options.headers || {}),
  };

  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const response = await fetch(url, {
    ...options,
    headers,
  });

  const contentType = response.headers.get('Content-Type') || '';
  const isJson = contentType.includes('application/json');

  if (!response.ok) {
    let message = `请求失败：${response.status}`;
    if (isJson) {
      try {
        const errorBody = await response.json();
        message = errorBody?.message || message;
      } catch (error) {
        // ignore
      }
    } else {
      try {
        const text = await response.text();
        if (text) message = text;
      } catch (error) {
        // ignore
      }
    }
    throw new Error(message);
  }

  if (!isJson) {
    return null;
  }

  const result = await response.json();
  return result?.data ?? result;
}

export const authService = {
  async login(payload) {
    return request(`${BASE_URL}/login`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async register(payload) {
    return request(`${BASE_URL}/register`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async refresh(refreshToken) {
    const url = `${BASE_URL}/refresh?refreshToken=${encodeURIComponent(
      refreshToken,
    )}`;
    return request(url, { method: 'POST' });
  },

  async logout() {
    try {
      await request(`${BASE_URL}/logout`, { method: 'POST' });
    } catch (error) {
      // 后端可能返回401，忽略即可
    }
  },

  async requestPasswordReset(email) {
    return request(`${BASE_URL}/password/forgot`, {
      method: 'POST',
      body: JSON.stringify({ email }),
    });
  },

  async resetPassword({ token, newPassword }) {
    return request(`${BASE_URL}/password/reset`, {
      method: 'POST',
      body: JSON.stringify({ token, newPassword }),
    });
  },

  async changePassword({ currentPassword, newPassword }) {
    return request(`${BASE_URL}/password/change`, {
      method: 'POST',
      body: JSON.stringify({ currentPassword, newPassword }),
    });
  },
};

